<template>
	<el-dialog title="选择图片" :visible.sync="imageModel" width="80%" top="5vh">
		<el-container style="height: 70vh;position: relative;margin: -30px -20px;">
			<el-header class="d-flex align-items-center border-bottom">
				<!-- header -->
				<div class="d-flex mr-auto ">
					<el-select v-model="searchForm.order" placeholder="图片排序方式" size="mini" style="width: 150px;margin-right: 10px;">
						<el-option label="降序" value="desc"></el-option>
						<el-option label="升序" value="asc"></el-option>
					</el-select>
					<el-input v-model="searchForm.keyword" placeholder="输入相册名称" size="mini" style="margin-right: 10px;width: 150px;"></el-input>
					<el-button type="primary" size="mini"
					@click="getImageList">搜索</el-button>
				</div>
				
			</el-header>
			<el-container>
				<el-aside width="200px" 
				style="position: absolute;top: 60px;left: 0;bottom: 60px;"
				class="bg-white border-right"
				v-loading="asideLoading">
					<!-- 侧边 -->
					<ul class="list-group list-group-flush">
						<album-item :item="item" :index="index"
						v-for="(item,index) in albums" :key="index"
						:active="albumIndex === index"
						@change="albumChange"
						:showOptions="false"
						></album-item>
					</ul>
				</el-aside>
				<el-container>
					<el-main style="position: absolute;top: 60px;left: 200px;bottom: 60px;right: 0;"
					v-loading="mainLoading">
						<!-- 主内容 -->
						<el-row :gutter="10">
							<el-col :span="24" :lg="4" :md="6" :sm="8"
							v-for="(item,index) in imageList" :key="index">
								<el-card class="box-card mb-3 position-relative" 
								:body-style="{'padding':'0'}"
								shadow="hover"
								style="cursor: pointer;">
									<div class="border " 
									:class="{'border-danger': item.isChecked}">
										<span class="badge badge-danger"
										style="position: absolute;top: 0;right: 0;"
										v-if="item.isChecked">{{item.checkOrder}}</span>
										<div @click="choose(item)">
											<img :src="item.url" class="w-100"  />
											<div class="w-100 text-white px-1" style="background: rgba(0,0,0,0.5);margin-top: -25px;position: absolute;">
												<span class="small">{{item.name}}</span>
											</div>
										</div>
										<div class="p-2 text-center">
											<el-button-group>
											  <el-button class="p-2" size="mini" icon="el-icon-edit"
											  @click="editImg(index, item)"></el-button>
											  <el-button class="p-2" size="mini" icon="el-icon-delete"
											  @click="multiDelImg({index: index})"></el-button>
											</el-button-group>
										</div>
									</div>
								</el-card>
							</el-col>
						</el-row>
					</el-main>
					
				</el-container>
			</el-container>
			<!-- footer -->
			<el-footer class="d-flex border-top align-items-center px-0">
				<div style="width: 200px;flex-shrink: 0;" class="h-100 d-flex align-items-center justify-content-center border-right">
					<el-button-group>
						<el-button size="mini" :disabled="albumPage === 1"
						@click="changeAlbumPage('pre')">上一页</el-button>
						<el-button size="mini"
						@click="changeAlbumPage('next')"
						:disabled="Math.ceil(albumTotall / 10) === albumPage">下一页</el-button>
					</el-button-group>
				</div>
				<div class="px-2" style="flex: 1;">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="currentPage"
						:page-sizes="pageSizes"
						:page-size="pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="total">
					</el-pagination>
				</div>
			</el-footer>
		</el-container>
		<span slot="footer" class="dialog-footer">
			<el-button @click="imageModel = false">取 消</el-button>
			<el-button type="primary" @click="confirm">确 定</el-button>
		</span>
	</el-dialog>
</template>

<script>
	import albumItem from "@/components/image/album-item.vue";
	export default {
		props: {
			max: {
				type: Number,
				default: 9
			}
		},
		components: {
			albumItem,
		},
		
		computed: {
			//选中相册的ID
			image_class_id() {
				let item = this.albums[this.albumIndex]
				if(item) {
					return item.id
				}
				return 0
			},
			
			//当前选中相册的图片列表URL
			getImageListUrl() {
				let other = ''
				if (this.searchForm.keyword !== '') {
					other = `&keyword=${this.searchForm.keyword}`
				}
				let searchUrl = `/admin/imageclass/${this.image_class_id}/image/${this.currentPage}?limit=${this.pageSize}&order=${this.searchForm.order}${other}`
				console.log(searchUrl)
				return searchUrl
			}
		},
		
		data() {
			return {
				imageModel: false,
				callback: false,
				
				value: '',
				searchForm: {
					order: '',
					keyword: ''
				},
				albums: [],
				albumIndex: 0,
				albumEditIndex: -1,
				albumTotall: 0,
				//相册当前页
				albumPage: 1,
			
				//图片列表
				imageList: [],
				//选中的数组
				checkImgList: [],
				//当前页
				currentPage: 1,
				
				//pageSize每页数据条数
				pageSize: 10,
				pageSizes: [10,20,50,100],
				total: 0,
				
				//loading
				asideLoading: false,
				mainLoading: false,
			}
		},
		
		// created() {
		// 	this.__initAlnums()
		// },
		
		methods: {
			//相册分页功能
			changeAlbumPage(type) {
				if(type === 'pre') {
					if (this.albumPage > 0) this.albumPage--
				} else {
					this.albumPage++
				}
				this.__initAlnums()
			},
			
			//打开弹出层
			showImageModel(callback) {
				
				this.__initAlnums()
				this.callback = callback
				this.imageModel = true
				//取消选中多张
				this.cancelImgCheck()
			},
			
			hide() {
				
				this.imageModel = false
				this.callback = false
			},
			confirm() {
				if (typeof this.callback === 'function' ) {
					this.callback(this.checkImgList)
				}
				//选中的图片url返回
				this.hide()
			},
			
			//取消选中多个图片
			cancelImgCheck() {
				//imgList
				this.imageList.forEach(img => {
					//找到选中图片的索引
					let i = this.checkImgList.findIndex(item => item.id === img.id)
					if (i > -1) {
						img.isChecked = false
						img.checkOrder = 0
					}
				})
				this.checkImgList = []
			},
			//分页方法
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
			},
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
			},
			
			//选中图片
			choose(item) {
				if (!item.isChecked) { //之前没有选中
					//限制选中数量
					if (this.checkImgList.length >= this.max) {
						return this.$message({
							message: '最多选择' + this.max + '张图片',
							type: 'warning'
						})
					}
					this.checkImgList.push({
						id: item.id,
						url: item.url,
						name: item.name
					})
					item.checkOrder = this.checkImgList.length
					item.isChecked = true
				} else if (item.isChecked) { //之前已经选中，取消选中
					//找到在选中列表中的索引
					let i = this.checkImgList.findIndex(v => v.id === item.id)
					if (i === -1) return
					//重新计算序号
					//是否是最后一个
					let len = this.checkImgList.length
					if (i + 1 < len) { //不是最后一个
						for (let j = i; j < len; j++) {
							let no = this.imageList.findIndex(v => v.id === this.checkImgList[j].id)
							if(no > -1) {
								this.imageList[no].checkOrder--
							}
						}
					}
					this.checkImgList.splice(i, 1)
					item.isChecked = false
					item.checkOrder = 0
				}
				
			},
			
			__initAlnums() {
				this.asideLoading = true
				this.axios.get('/admin/imageclass/' + this.albumPage, {token: true})
					.then(res => {
						let result = res.data.data
						this.albums = result.list
						this.albumTotall = result.totalCount
						//获取选中相册下第一页的相册列表
						this.getImageList()
						this.asideLoading = false
					}).catch(err => {
						this.asideLoading = false
					})
				
			},
			
			//获取对应相册下的图片列表
			getImageList() {
				//获取相册列表
				this.mainLoading = true
				this.axios.get(this.getImageListUrl, {token: true})
					.then(res => {
						let result = res.data.data
						this.imageList = result.list.map(item => {
							return {
								id: item.id,
								url: item.url,
								name: item.name,
								isChecked: false,
								checkOrder:0
							}
						})
						this.total = result.totalCount
						this.mainLoading = false
					}).catch(err => {
						this.mainLoading = false
					})
			},
			
			// __initAlnums() {
			// 	for (var i = 0; i < 20; i++) {
			// 		this.albums.push({
			// 			name: '相册' + i,
			// 			num: i,
			// 			order: 0
			// 		})
			// 	}
			// 	//初始化图片列表
			// 	for (let i = 0; i < 30; i++) {
			// 		this.imageList.push({
			// 			id: i,
			// 			url: "https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1581494045.31058391.jpg",
			// 			name: '小米10-' + i,
			// 			isChecked: false,
			// 			checkOrder: 0
			// 		})
			// 	}
			// },
			//切换相册
			albumChange(index) {
				this.albumIndex = index
				this.getImageList()
			},
			
			//修改相册
			updateAlbum() {
				this.albums[this.albumEditIndex].name = this.albumForm.name
				this.albums[this.albumEditIndex].order = this.albumForm.order
			},
			
			//点击确定修改 ｜ 新增相册
			confirmAlbumModel() {
				//判断是否是修改
				if(this.albumEditIndex > -1) {
					this.updateAlbum()
					return this.albumModel = false
				}
				if(!this.albumForm.name || this.albumForm.name.trim() === '') {
					return this.$message({
						message: '相册名称不能为空',
						type: 'error'
					})
				}
				this.albums.unshift({
					name: this.albumForm.name,
					num: 0,
					order: this.albumForm.order
				})
				this.albumModel = false
			},
			//删除相册
			delAlbum(index) {
				
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.albums.splice(index,1)
					this.$message({
					type: 'success',
					message: '删除成功!'
					});
				}).catch(() => {
					this.$message({
					type: 'info',
					message: '已取消删除'
					});
				});
			},
			//打开相册 修改 ｜ 新增model
			openAlbumModel({index, item}) {
				//修改
				if(item) {
					this.albumForm.name = item.name
					this.albumForm.order = item.order
					this.albumEditIndex = index
					return this.albumModel = true
				}
				//创建
				this.albumForm = {name: '', order: 0}
				this.albumEditIndex = -1
				this.albumModel = true
			},
			
			//删除图片
			delImg(index) {
				this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.imageList.splice(index, 1)
					this.$message({
					type: 'success',
					message: '删除成功!'
					});
				}).catch(() => {
					this.$message({
					type: 'info',
					message: '已取消删除'
					});
				});
			},
			
			//修改图片名称
			editImg(index,item) {
				this.$prompt('请输入图片名称', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  inputPattern: /\s*\S+?/,
				  inputErrorMessage: '图片名称不能为空',
				  inputValue: item.name
				}).then(({ value }) => {
					item.name = value
				  this.$message({
					type: 'success',
					message: '修改图片名称成功'
				  });
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '取消输入'
				  });       
				});
			},
			
			multiDelImg({multiDel = false, index}) {
				
				this.$confirm('确定删除选中图片?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					if(multiDel) {
						if(this.checkImgList.length === 0) {
							return this.$message({
								message: '您还没有选中的图片',
								type: 'error'
							});
						}
						this.imageList = this.imageList.filter(img => {
							return !this.checkImgList.some(v => v.id === img.id)
						})
						this.checkImgList = []
					} else {
						this.imageList.splice(index, 1)
					}
					this.$message({
					type: 'success',
					message: '删除成功!'
					});
				}).catch(() => {
					this.$message({
					type: 'info',
					message: '已取消删除'
					});
				});
				
			},
		},
	}
</script>

<style>
</style>
